package com.action;

import com.alibaba.fastjson.JSONObject;
import com.pojo.RoleJurisdiction;
import com.pojo.User;
import com.service.RoleJurisdictionService;
import com.service.ShiroService;
import com.service.UserService;
import com.token.JwtUtil;
import com.vo.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@CrossOrigin("*")
@RequestMapping("/admin")
public class RoleJurisdictionAction {
    @Autowired
    private RoleJurisdictionService jurisdictionService;
    @Autowired
    private UserService userService;
    @Autowired
    private ShiroService shiroService;


    @RequestMapping("/addRole")
    public ResponseBean add(String strlist){
        System.out.println(strlist);
        List<RoleJurisdiction> list = JSONObject.parseArray(strlist,RoleJurisdiction.class);
        shiroService.reloadRole(list);
        boolean b = jurisdictionService.saveOrUpdateBatch(list);
        if(b){
            return new ResponseBean(200,0,"添加成功");
        }
        return new ResponseBean(500,0,"添加失败");
    }

    @RequestMapping("/updateRole")
    public ResponseBean updateRole(String userName, int roleId, HttpServletRequest req){
        String editor = JwtUtil.getUsername(req.getHeader("token"));
        User u = userService.findUser(editor);
        if(u.getRoleId()<roleId){
            return new ResponseBean(403,0,"对不起，您没有权限！");
        }else{
            userService.updateRole(userName,roleId);
        }
        return new ResponseBean(200,0,"修改成功");
    }

    @RequestMapping("/selectRoleNameAndUsername")
    public ResponseBean selectRoleNameAndUsername(String userName){
        return new ResponseBean(0,0,jurisdictionService.selectRoleNameAndUsername(userName));
    }

    @RequestMapping("/selectJurisdictionName")
    public ResponseBean selectJurisdictionName(){
        return new ResponseBean(200,0,jurisdictionService.selectJurisdictionName());
    }


    @RequestMapping("/selectRole")
    public ResponseBean selectRole(){
        return new ResponseBean(0,0,jurisdictionService.selectRole());
    }

    @RequestMapping("/saveRolesResources")
    public ResponseBean saveRolesResources(String strlist){
        List<RoleJurisdiction> list = JSONObject.parseArray(strlist,RoleJurisdiction.class);
        shiroService.reloadRole(list);
        return new ResponseBean(200,0,jurisdictionService.saveOrUpdateBatch(list));
    }
}
